package zhengyanze.com.aipoemmax.guide.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zhengyanze.com.aipoemmax.R;
import zhengyanze.com.aipoemmax.guide.Constant;
import zhengyanze.com.aipoemmax.guide.bean.LeiXingBean;
import zhengyanze.com.aipoemmax.guide.bean.PoemBean;
import zhengyanze.com.aipoemmax.guide.bean.PoemBean2;
import zhengyanze.com.aipoemmax.guide.fragment.Four1Fragment;
import zhengyanze.com.aipoemmax.guide.fragment.Four2Fragment;
import zhengyanze.com.aipoemmax.guide.fragment.Four3Fragment;
import zhengyanze.com.aipoemmax.guide.utils.LocationUtils;
import zhengyanze.com.aipoemmax.guide.utils.TypefaceUtil;

public class PoemDetilsActivity extends AppCompatActivity {
    public static final String POEM_KEY = "poem.key";
    public static final String MINGJU_KEY = "mingju.key";
    public static final String POEM_FRAGMENT_KEY = "poem.fragment.key";
    private static final String TAG = "PoemDetilsActivity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_wen)
    Button btnWen;
    @BindView(R.id.btn_zhu)
    Button btnZhu;
    @BindView(R.id.btn_shang)
    Button btnShang;
    @BindView(R.id.btn_cang)
    Button btn_cang;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    private ArrayList<Button> mButtons;
    private Four1Fragment four1Fragment;
    private Four2Fragment four2Fragment;
    private Four3Fragment four3Fragment;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private PoemBean poemBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poem_detils);
        ButterKnife.bind(this);

        Bundle bund = getIntent().getExtras();

        four1Fragment = new Four1Fragment();
        four2Fragment = new Four2Fragment();
        four3Fragment = new Four3Fragment();
        if (bund.containsKey(POEM_KEY)) {
            poemBean = getIntent().getParcelableExtra(POEM_KEY);
            //判断是不是我的随笔
            if ("Mysuibi".equals(poemBean.getLink())) {
                btnWen.setVisibility(View.GONE);
                btnShang.setVisibility(View.GONE);
                btnZhu.setVisibility(View.GONE);
            }
            initView(poemBean.getTitle());
            Bundle bundle = new Bundle();
            bundle.putParcelable(POEM_FRAGMENT_KEY, poemBean);

            four1Fragment.setArguments(bundle);
            four2Fragment.setArguments(bundle);
            four3Fragment.setArguments(bundle);
            switchSelect(0, four1Fragment);

        } else if (bund.containsKey(MINGJU_KEY)) {
            LeiXingBean bean = getIntent().getParcelableExtra(MINGJU_KEY);
            if (bean != null) {
                String url = bean.getLink();
                initView2(url);
                initView(bean.getContent());
            } else {
                Toast.makeText(this, "加载失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 初始化布局
     *
     * @param titled
     */
    public void initView(String titled) {
        setSupportActionBar(toolbar);
        setTitle("");
        toolbar.setNavigationIcon(R.mipmap.title_back_normal);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvTitle.setText(titled);
        TypefaceUtil util = new TypefaceUtil(this, Constant.TTF.TTF_MAIN_TYPE);
        util.setTypeface(tvTitle, false);

        mButtons = new ArrayList<>();
        mButtons.add(btnWen);
        mButtons.add(btnZhu);
        mButtons.add(btnShang);
    }

    int lastPosition = -1;

    @OnClick({R.id.btn_wen, R.id.btn_zhu, R.id.btn_shang, R.id.btn_cang})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_wen:
                switchSelect(0, four1Fragment);
                lastPosition = 0;
                break;
            case R.id.btn_zhu:
                switchSelect(1, four2Fragment);
                lastPosition = 1;
                break;
            case R.id.btn_shang:
                switchSelect(2, four3Fragment);
                lastPosition = 2;
                break;
            case R.id.btn_cang:
                //收藏诗词到本地
                locationCollect();
                break;
        }
    }

    /**
     * 选择
     *
     * @param position
     * @param fragment
     */
    private void switchSelect(int position, Fragment fragment) {
        if (position == lastPosition) {
            return;
        }
        for (int i = 0; i < mButtons.size(); i++) {
            if (position == i) {
                mButtons.get(i).setSelected(true);
            } else {
                mButtons.get(i).setSelected(false);
            }
        }
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        for (int i = 0; i < mFragments.size(); i++) {
            transaction.hide(mFragments.get(i));
        }
        if (fragment.isAdded()) {
            transaction.show(fragment);
        } else {
            mFragments.add(fragment);
            transaction.add(R.id.fl_content, fragment);
        }
        transaction.commit();
    }

    /**
     * 请求古诗详情
     */
    public void initView2(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.connect(url).get();
                    Element main3 = document.getElementsByClass("main3").first();
                    Element left = main3.getElementsByClass("left").first();
                    Element sons = left.getElementsByClass("sons").first();
                    Element cont = sons.getElementsByClass("cont").first();

                    Element h1 = cont.getElementsByTag("h1").first();
//                    Log.e(TAG, "标题是: " + h1.text());

                    Element p = cont.getElementsByTag("p").first();
//                    Log.e(TAG, "作者是: " + p.text());

                    Element contson = cont.getElementsByClass("contson").last();
//                    Log.e(TAG, "内容是是: " + contson.text());

                    poemBean = new PoemBean(h1.text(), p.text(), contson.text(), url);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Bundle bundle = new Bundle();
                            bundle.putParcelable(POEM_FRAGMENT_KEY, poemBean);

                            four1Fragment.setArguments(bundle);
                            four2Fragment.setArguments(bundle);
                            four3Fragment.setArguments(bundle);
                            switchSelect(0, four1Fragment);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //收藏诗词到本地
    private void locationCollect() {
        LocationUtils utils = LocationUtils.getLocation(this);
        PoemBean2 poemBean2 = new PoemBean2(poemBean.getTitle(), poemBean.getAuthor(), poemBean.getContent(), poemBean.getLink());
        ArrayList<PoemBean2> mPoemBeens = utils.getFile();
        if (mPoemBeens != null && !mPoemBeens.isEmpty()) {
            for (PoemBean2 bean : mPoemBeens) {
                if (bean.equals(poemBean2)) {
                    Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show();
                    btn_cang.setSelected(true);
                    return;
                }
            }
        }
        if (mPoemBeens == null) {
            mPoemBeens = new ArrayList<>();
        }
        mPoemBeens.add(poemBean2);
        utils.saveFile(mPoemBeens);
        btn_cang.setSelected(true);
        Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
    }
}
